from fastapi import APIRouter, Depends,Form
from model.admin import Admin,LoginForm
from sqlalchemy.orm import Session
from db.mysql import get_db
from vendor.extend.courier import *
from vendor.extend.auth import get_password_hash,verify_password,create_access_token
from loguru import logger

AdminUser = APIRouter()

@AdminUser.post("/login/")
async def login(response: LoginForm, db: Session = Depends(get_db)):
    user = db.query(Admin).filter_by(account = response.account).first()
    if not user:
        return Error(msg='管理员不存在')
    if not verify_password(response.password, user.password):
        return Error(msg='管理员密码错误')
    access_token = create_access_token(
        data={"sub": response.account}
    )
    ret = {
        "access_token": access_token, "token_type": "bearer"
    }
    return Success(msg='管理员登录成功',data=ret)

@AdminUser.post("/register")
async def register(user: LoginForm, db: Session = Depends(get_db)):
    if db.query(Admin).filter_by(account=user.account).count() > 0:
        return Error(msg='管理员已存在')

    db_user = db.query(Admin).filter_by(account=user.account, password=get_password_hash(user.password))

    try:
        # 执行一些数据库操作
        db.add(db_user)
        db.commit()
    except Exception as e:
        # 手动回滚会话并重新抛出异常
        db.rollback()
        logger.error("注册 管理员 出错:{}", e)

    return Success(msg='管理员注册成功')


# @AdminUser.get("/test")
# async def test():
#     return get_password_hash('850281')
